const axios = require('axios');


// 彩票机选函数
function getNumber(count,border) {
  var nums = []
  for (i = 0; i < count; i++){
    let random = Math.floor((Math.random() * border)) + 1
    while (nums.includes(random)) {
      random = Math.floor((Math.random() * border)) + 1
    }
    nums.push(random)
  }
  return nums
}

// 福利彩票
function welfareLottery(type) {
  let result = ''
  // type 1-双色球
  switch (type) {
    case 1:
      result = `${[...getNumber(6,33)].join(', ')} | ${[...getNumber(1,16)].join(', ')}`
    default:
      break;
  }
  return result
}

// 体育彩票
function sportLottery(type) {
  let result = ''
  // type 1-大乐透
  switch (type) {
    case 1:
      result = `${[...getNumber(5,35)].join(', ')} | ${[...getNumber(2,12)].join(', ')}`
    default:
      break;
  }
  return result
}

// 机选
function selectLotteryNums(company,type) {
  // company - 彩票公司 type - 类别
  if (company === 1) {
    // 福利彩票
    return welfareLottery(type)
  }
  if (company === 2) {
    // 体育彩票
    return sportLottery(type)
  }
  return ""
}

// 获得中奖结果-最新一期
function getLotteryData(type) {
  // type 1-双色球 2-大乐透
  if (type === 1) {
    return new Promise((reslove,reject) => {
      axios.get('https://m.daguoxiaoxian.com/wechat-api/winInfo/list?lotNo=1001&pageIndex=1&maxResult=1').then(res => {
        const result = JSON.parse(res.data.slice(1, -1)).value.result[0].winCode
        const arr1 = result.split('|')[0].split(',')
        const arr2 = result.split('|')[1].split(',')
        reslove([arr1,arr2])
      }).catch(err => {
        reject(err)
      })
    })
  }
  if (type === 2) {
    return new Promise((reslove,reject) => {
      axios.get('https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=1&isVerify=1&termLimits=0&pageNo=1')
        .then(res => {
        const result = res.data.value.list[0].lotteryDrawResult
        const arr1 = result.split(' ').splice(0,5)
        const arr2 = result.split(' ').splice(5)
        reslove([arr1,arr2])
      }).catch(err => {
        reject(err)
      })
    })
  }
}

module.exports = {
  selectLotteryNums,
  getLotteryData
}
